package com.coolweather.android.util

import android.text.TextUtils
import com.coolweather.android.db.City
import com.coolweather.android.db.County
import com.coolweather.android.db.Province
import com.coolweather.android.gson.Weather
import com.google.gson.Gson
import org.json.JSONArray
import org.json.JSONObject

/**
 * @author by liliang on 2020/6/4 12:40 PM
 */
object Utility {

    /**
     * 解析服务器返回的省级数据  保存到本地数据库
     * @param response json 省级 json 数据
     */
    fun handleProvinceResponse(response: String?): Boolean {
        if (!TextUtils.isEmpty(response)) {
            val jsonArray = JSONArray(response)
            for (i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                Province().apply {
                    provinceName = jsonObject.getString("name")
                    provinceCode = jsonObject.getInt("id")
                }.save()
            }
            return true
        }
        return false
    }

    /**
     * 解析服务器返回的市级数据  保存到本地数据库
     * @param response json 市级 json 数据
     * @param provinceId 省份 id
     */
    fun handleCityResponse(response: String?, provinceId: Int): Boolean {
        if (!TextUtils.isEmpty(response)) {
            val jsonArray = JSONArray(response)
            for (i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                val city = City().apply {
                    cityName = jsonObject.getString("name")
                    cityCode = jsonObject.getInt("id")
                    this.provinceId = provinceId
                }.save()
            }
            return true
        }
        return false
    }

    /**
     * 解析服务器返回的市级数据 保存到本地数据库
     * @param response json 县级 json 数据
     * @param cityId 城市 id
     */
    fun handleCountyResponse(response: String?, cityId: Int): Boolean {
        if (!TextUtils.isEmpty(response)) {
            val jsonArray = JSONArray(response)
            for (i in 0 until jsonArray.length()) {
                val jsonObject = jsonArray.getJSONObject(i)
                County().apply {
                    countyName = jsonObject.getString("name")
                    weatherId = jsonObject.getString("weather_id")
                    this.cityId = cityId
                }.save()
            }
            return true
        }
        return false
    }

    /**
     * 解析天气 JSON 数据
     * @param  response 天气 JSON 字符串
     * @return Weather 对象
     */
    fun handleWeatherResponse(response: String) : Weather {
        try {
            val jsonObject = JSONObject(response)
            val jsonArray = jsonObject.getJSONArray("HeWeather")
            val weatherContent = jsonArray.getJSONObject(0).toString()
            return Gson().fromJson(weatherContent, Weather::class.java)
        } catch (e: Exception) {
            throw RuntimeException("json 解析异常$e")
        }
    }
}